import { computed, onMounted, onUnmounted, ref } from "vue";

const useFilter = (todos) => {
  const allDone = computed({
    get() {
      return !todos.value.filter((item) => !item.completed).length;
    },
    set(value) {
      todos.value.forEach((item) => {
        item.completed = value;
      });
    },
  });

  const filter = {
    all: (list) => list,
    active: (list) => list.filter((item) => !item.completed),
    completed: (list) => list.filter((item) => item.completed),
  };

  const type = ref("all");

  const filteredTodos = computed(() => filter[type.value](todos.value));

  const remainingCount = computed(() => filter.active(todos.value).length);

  const count = computed(() => todos.value.length);

  const onHashChange = () => {
    const hash = window.location.hash.replace("#/", "");
    if (filter[hash]) {
      type.value = hash;
    } else {
      type.value = "all";
      window.location.hash = "";
    }
  };

  onMounted(() => {
    onHashChange();
    window.addEventListener("hashchange", onHashChange);
  });

  onUnmounted(() => {
    window.removeEventListener("hashchange", onHashChange);
  });

  return {
    count,
    filteredTodos,
    remainingCount,
    allDone,
  };
};

export default useFilter;
